import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-09-16
 * Time: 0:46
 */

/**
 * 罗马数字转整数:
 */
public class RomanNumbers {
    public static int romanToInt(String s) {
        Map<Character,Integer> hash = new HashMap<>();
        hash.put('I',1);
        hash.put('V',5);
        hash.put('X' ,10);
        hash.put('L' ,50);
        hash.put('C',100);
        hash.put('D',500);
        hash.put('M' ,1000);

        int ret = 0;
        char[] ch = s.toCharArray();

        // 思路：遍历字符，如果该字符的val小于前一个字符的val就做减法，反之做加法
        for(int i = 0; i < ch.length; i++){
            if(i+1 < ch.length){
                if(hash.get(ch[i]) < hash.get(ch[i+1])){
                    ret -= hash.get(ch[i]);
                }else {
                    ret += hash.get(ch[i]);
                }
            }else {
                ret += hash.get(ch[i]);
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        String s = "III";
        romanToInt(s);
    }
}
